#!/usr/bin/bash
# Copyright (c) 2023. huawei Technologies Co.,Ltd.ALL rights reserved.
# This program is licensed under Mulan PSL v2.
# You can use it according to the terms and conditions of the Mulan PSL v2.
#          http://license.coscl.org.cn/MulanPSL2
# THIS PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
# #############################################
# @Author    :   zhuwenshuo
# @Contact   :   1003254035@qq.com
# @Date      :   2023/02/21
# @License   :   Mulan PSL v2
# @Desc      :   Test zentest
# #############################################
source "$OET_PATH/libs/locallibs/common_lib.sh"
GEM_PACKAGES=" rubygem-test-unit rubygem-ZenTest rubygem-minitest rubygem-rails "
OTHER_DEPENDENCES=" tar nodejs bc gcc libyaml-devel ruby-devel "
SOURCE_URL="https://gems.ruby-china.com/"
ORIGIN_SOURCE="https://rubygems.org/"
function pre_test() {
    LOG_INFO "Start to prepare the test environment."
    # remove
    sudo dnf autoremove -y gem
    # install
    DNF_INSTALL "${GEM_PACKAGES} ${OTHER_DEPENDENCES}"
    gem sources --add ${SOURCE_URL} --remove ${ORIGIN_SOURCE}
    bundle config mirror.${ORIGIN_SOURCE} ${SOURCE_URL}
    sudo yum groupinstall "Development Tools" -y
    tar -xvf ./common/data.tar.gz >/dev/null
    LOG_INFO "End to prepare the test environment."
}
function run_test() {
    LOG_INFO "Start to run test."
    zentest -h | grep "ZenTest scans your target"
    CHECK_RESULT $? 0 0 "Check zentest -h failed"
    zentest -v | grep "$(rpm -qa rubygem-ZenTest | awk -F '-' '{print $3}')"
    CHECK_RESULT $? 0 0 "Check zentest -v failed"
    zentest ./data/example1.rb ./data/example2.rb | grep "Code Generated by ZenTest"
    CHECK_RESULT $? 0 0 "Check zentest basic failed"
    zentest -e ./data/example1.rb | grep "NotImplementedError"
    CHECK_RESULT $? 0 0 "Check zentest -e failed"
    zentest -t ./data/example1.rb | grep "class TestThingy < Test::Unit::TestCase"
    CHECK_RESULT $? 0 0 "Check zentest -t failed"
    version=$(ruby --version | awk '{print $2}' | cut -c1-3)
    if [[ $(echo "${version} >= 2.6" | bc) -eq 1 ]] && [[ $(echo "${version} < 4.0" | bc) -eq 1 ]]; then
        rails new demo --minimal --skip-bundle
        pushd demo || exit
        bundle config set --local path 'vendor/bundle'
        bundle add concurrent-ruby -v 1.3.4 # concurrent-ruby 1.3.5 bug https://github.com/rails/rails/issues/54260
        bundle install
        zentest -r ./db/seeds.rb | grep "Number of errors"
        CHECK_RESULT $? 0 0 "Check zentest -r failed"
        popd || exit
    fi
    LOG_INFO "End to run test."
}
function post_test() {
    LOG_INFO "Start to restore the test environment."
    DNF_REMOVE "$@"
    rm -rf lib/ data/ demo
    LOG_INFO "End to restore the test environment."
}
main "$@"
